package com.eduadmin.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.eduadmin.entity.Exam;
import com.eduadmin.entity.StatisticsParamiter;
import com.eduadmin.exception.CustomException;
import com.eduadmin.service.IExamService;
import com.eduadmin.service.IStatisticsParamiterService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class StatisticsParamiterDataUploadListener extends AnalysisEventListener<StatisticsParamiter> {
    private int count=1;
    private final IStatisticsParamiterService statisticsParamiterService;
    private final IExamService examService;

    public StatisticsParamiterDataUploadListener(IExamService examService, IStatisticsParamiterService statisticsParamiterService) {
        this.statisticsParamiterService = statisticsParamiterService;
        this.examService = examService;
    }

    List<StatisticsParamiter> list = new ArrayList<>();

    @Override
    public void invoke(StatisticsParamiter data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        count++;
        Map<String,Object> paraMap=new HashMap<>();
        paraMap.put("gradeName",data.getGradeName());
        paraMap.put("semesterName",data.getSemesterName());
        paraMap.put("examName",data.getExamName());
        Exam exam= examService.getExamByParams(paraMap);// zlc 更改2021-12-17
        if(exam==null){
            throw new CustomException("adminindex","Excel表格中第 " +count +" 行的考试名称不在考试信息中，请先导入考试信息！",null);
        }
        int n = statisticsParamiterService.getStatisticsParamiterByExamName(data.getExamName());
        if(n==1){
            throw new CustomException("adminindex","Excel表格中第 " +count +" 行的考试名称 和系统中重名！不能导入",null);
        }
        list.add(data);
        saveData();
        list.clear();
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    //存储数据库
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", this.count);
        if (!CollectionUtils.isEmpty(list)) {
            statisticsParamiterService.addStatisticsParamiter(list);
        }
        log.info("存储数据库成功！");
    }


}
